package com.jqb.jspcart.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jqb.jspcart.bean.Hardware;
import com.jqb.jspcart.service.impl.CartServiceImpl;
import com.jqb.jspcart.service.impl.OrderServiceImpl;

public class OrderServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opt = request.getParameter("opt");
		String user = (String) request.getSession().getAttribute("user");
		if(user==null||"".equals(user)){
			request.setAttribute("msg","请先登录...");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}else{
			//显示订单
			if("show".equals(opt)){
				CartServiceImpl cart = (CartServiceImpl)request.getSession().getAttribute("cart");
				ArrayList<Hardware> goodsList = cart.getGoods();
				request.setAttribute("goodsList", goodsList);
				request.setAttribute("sum", cart.getSum());
				request.getRequestDispatcher("order.jsp").forward(request, response);	
			}
			//生成订单入库
			if("create".equals(opt)){
				CartServiceImpl cart = (CartServiceImpl)request.getSession().getAttribute("cart");
				String username = (String)request.getSession().getAttribute("user");
				System.out.println("creating order...");
				boolean flag = OrderServiceImpl.newInstance().createOrder(cart, username);
				if(flag){
					request.getSession().removeAttribute("cart");
					request.getRequestDispatcher("deal.jsp").forward(request, response);
				}else{
					request.getRequestDispatcher("error.jsp").forward(request, response);
				}
			}
			
		}
	}
}
